import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import Textarea from '@/components/Textarea';
import { useAppSelector } from '@/store';
import {
  actionEditProfile,
  actionfiles,
  actionUserProfile,
} from '@/store/action/user';
import { Profile } from '@/store/reducer/user';
import { removeToken } from '@/utils/local';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';

import styles from './index.module.scss';
type editType = 'photo' | 'gender' | 'name' | 'mobile' | 'intro' | 'birthday';
export default function Edit() {
  const history = useHistory();
  const { profile } = useAppSelector((state) => state.user);
  const inputRef = useRef<HTMLInputElement>(null);
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(actionUserProfile());
  }, [dispatch]);
  //监听回显
  useEffect(() => {
    setName(profile.name || '');
  }, [profile.name]);
  useEffect(() => {
    setIntro(profile.intro || '');
  }, [profile.intro]);
  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [showBirthday, setShowBirthday] = useState(false);
  const [editType, setEditType] = useState('' as editType);
  // 昵称input值
  const [name, setName] = useState('');
  const [intro, setIntro] = useState('');
  const isShowRightVisible = (type: editType) => {
    setRightVisible(false);
    setEditType(type);
    editType === 'name' && setName(profile.name);
    editType === 'intro' && setIntro(profile.intro || '');
  };
  const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
    // console.log(`e.target.file[0]`, e.target.files && e.target.files[0]);

    if (e.target.files) {
      const formData = new FormData();
      formData.append('photo', e.target.files[0]);
      await dispatch(actionfiles(formData));
      setVisible(false);
      Toast.show({ content: '更新成功' });
    }
  };
  const handleEditProfile = async (data: Partial<Profile>) => {
    await dispatch(actionEditProfile(data));
    setVisible(false);
    setRightVisible(false);
    setShowBirthday(false);
    Toast.show({ content: '更新成功' });
  };
  //退出登录
  const handleLogout = () => {
    Dialog.confirm({
      title: '退出登录',
      content: '确认退出登录吗',
      onConfirm: () => {
        removeToken();
        history.push('/login');
        Toast.show({ content: '退出成功' });
      },
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => {
                setVisible(true);
                setEditType('photo');
              }}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => {
                setRightVisible(true);
                setEditType('name');
              }}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={
                <span className="intro">
                  {profile.intro ? profile.intro : '未填写'}
                </span>
              }
              onClick={() => {
                setRightVisible(true);
                setEditType('intro');
              }}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 1 ? '男' : '女'}
              onClick={() => {
                setVisible(true);
                setEditType('gender');
              }}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => {
                setShowBirthday(true);
                setEditType('birthday');
              }}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            ref={inputRef}
            className="avatar-upload"
            type="file"
            onChange={handleFile}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLogout}>
            退出登录
          </button>
        </div>
      </div>
      {/* 下侧弹出层 */}
      <Popup
        visible={visible}
        position="bottom"
        bodyClassName="popup-bottom-list"
        onMaskClick={() => setVisible(false)}
      >
        {editType === 'photo' && (
          <>
            <div
              className="list-item"
              onClick={() => inputRef.current?.click()}
            >
              拍照
            </div>
            <div
              className="list-item"
              onClick={() => inputRef.current?.click()}
            >
              本地选择
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        )}
        {editType === 'gender' && (
          <>
            <div
              className="list-item"
              onClick={() => handleEditProfile({ gender: 1 })}
            >
              男
            </div>
            <div
              className="list-item"
              onClick={() => handleEditProfile({ gender: 0 })}
            >
              女
            </div>
            <div className="list-item" onClick={() => setVisible(false)}>
              取消
            </div>
          </>
        )}
      </Popup>
      {/* 右侧弹出层 */}
      <Popup
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
        destroyOnClose
      >
        {(editType === 'name' || editType === 'intro') && (
          <>
            <NavBar
              right={
                <span
                  className="submit-btn"
                  onClick={() =>
                    handleEditProfile({
                      [editType]: editType === 'name' ? name : intro,
                    })
                  }
                >
                  提交
                </span>
              }
              onBack={() => isShowRightVisible(editType)}
            >
              {editType === 'name' ? '编辑昵称' : '编辑简介'}
            </NavBar>
            <div className="edit-content">
              {editType === 'name' ? (
                <Input
                  className="edit-input"
                  autoFocus
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                />
              ) : (
                <Textarea
                  value={intro}
                  onChange={(e) => setIntro(e.target.value)}
                ></Textarea>
              )}
            </div>
          </>
        )}
      </Popup>
      <DatePicker
        visible={showBirthday}
        onClose={() => {
          setShowBirthday(false);
        }}
        // defaultValue={now}
        value={new Date(profile.birthday)}
        min={new Date('1990-1-1')}
        max={new Date()}
        onConfirm={(val) => {
          handleEditProfile({ birthday: dayjs(val).format('YYYY-MM-DD') });
          // Toast.show(val.toDateString());
        }}
      />
    </div>
  );
}
